package com.byp.java_sport.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.byp.java_sport.config.annotation.RestControllerMapping;
import com.byp.java_sport.model.Result;
import com.byp.java_sport.pojo.SysUser;
import com.byp.java_sport.pojo.vo.Login;
import com.byp.java_sport.service.SysUserService;
import com.byp.java_sport.utils.PasswordUtils;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;

@RestControllerMapping("login")
public class LoginController {

    @Resource
    private SysUserService userService;
    @SaIgnore
    @PostMapping("user")
    @Operation(summary = "用户账号密码登录")
    public Result<Map<String,String>> login(@RequestBody Login login){

        SysUser user = userService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, login.getUsername()));
        if(user ==null){
            return Result.error("账号密码错误");
        }
        //校验密码是否正确
        String password = login.getPassword();
        if(PasswordUtils.decrypt(user.getSlat(),user.getPassword()).equals(password)){
            //登录
            StpUtil.login(user.getId());
            //登陆完了以后还要返回Token
            SaTokenInfo info = StpUtil.getTokenInfo();
            Map<String,String> map = new HashMap<>();
            map.put("tokenHead",info.getTokenName());
            map.put("token",info.getTokenValue());
            return Result.success(map);
        }
        return Result.error("账号密码错误");
    }
    @GetMapping("logout")
    @Operation(summary = "退出登录")
    public Result<Boolean> logout(){
        StpUtil.logout();
        return Result.success();
    }
    @GetMapping("test")
    @Operation(summary = "用户测试")
    @SaCheckPermission("login:test")
    public Result<String> test(){

        return Result.success("测试成功");
    }
}
